<template>
  <el-form
    ref="FormRef"
    :model="formData"
    :rules="formColumn.rules"
    :label-width="formColumn.labelWidth"
    :size="formColumn.size"
    :status-icon="formColumn.statusIcon"
    :label-position="formColumn.labelPosition"
    :scroll-to-error="formColumn.scrollToError"
    :validate-on-rule-change="formColumn.validateOnRuleChange"
  >
    <el-row :gutter="24">
      <el-col
        v-for="(item, index) in formColumn.items"
        :key="index"
        :span="item.span"
      >
        <el-form-item
          v-if="item.inputType == 'input'"
          :label="item.label"
          :prop="item.prop"
        >
          <el-input
            v-model="formData[item.prop]"
            :placeholder="item.placeholder"
            :clearable="item.clearable"
            :disabled="item.disabled"
            :prefixIcon="item.prefixIcon"
            :suffixIcon="item.suffixIcon"
            :readonly="item.readonly"
            :type="item.type"
          />
        </el-form-item>
        <el-form-item
          v-if="item.inputType == 'select'"
          :label="item.label"
          :prop="item.prop"
        >
          <el-select
            v-model="formData[item.prop]"
            :placeholder="item.placeholder"
            :clearable="item.clearable"
            :disabled="item.disabled"
            :readonly="item.readonly"
            :multiple="item.multiple"
            :collapse-tags="item.collapseTags"
            :collapse-tags-tooltip="item.collapseTagsTooltip"
            :filterable="item.filterable"
            :filter-method="item.filterMethod"
            :remote="item.remote"
            :remote-method="item.remoteMethod"
            @change="changeForm(item.prop, formData[item.prop], item.option)"
          >
            <el-option
              v-for="(op, i) in item.option"
              :label="op.label"
              :value="op.value"
              :key="i"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="item.inputType == 'date'"
          :label="item.label"
          :prop="item.prop"
        >
          <el-date-picker
            v-model="formData[item.prop]"
            :type="item.type"
            :placeholder="item.placeholder"
            :clearable="item.clearable"
            :disabled="item.disabled"
            :readonly="item.readonly"
            :start-placeholder="item.startPlaceholder"
            :end-placeholder="item.endPlaceholder"
            :format="item.format"
            :range-separator="item.rangeseparator"
            :value-format="item.valueFormat"
            :unlink-panels="item.unlinkPanels"
            :disabled-date="item.disabledDate"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item
          v-if="item.inputType == 'treeselect'"
          :label="item.label"
          :prop="item.prop"
        >
          <el-tree-select
            v-model="formData[item.prop]"
            :placeholder="item.placeholder"
            :clearable="item.clearable"
            :disabled="item.disabled"
            :readonly="item.readonly"
            :multiple="item.multiple"
            :collapse-tags="item.collapseTags"
            :collapse-tags-tooltip="item.collapseTagsTooltip"
            :filterable="item.filterable"
            :filter-method="item.filterMethod"
            :data="item.data"
            :render-after-expand="item.renderAfterExpand"
            :show-checkbox="item.showCheckbox"
            :empty-text="item.emptyText"
            :props="item.props"
            :load="item.load"
            :render-content="item.renderContent"
            :expand-on-click-node="item.expandOnClickNode"
            :check-on-click-node="item.checkOnClickNode"
            :default-expanded-keys="item.defaultExpandedKeys"
            :check-strictly="item.checkStrictly"
            :default-checked-keys="item.defaultCheckedKeys"
            :icon="item.icon"
            :lazy="item.lazy"
          />
        </el-form-item>
        <el-form-item
          v-if="item.inputType == 'mdEditer'"
          :label="item.label"
          :prop="item.prop"
        >
        <MdEditor v-model="formData[item.prop]" @onUploadImg="onUploadImg" />
        </el-form-item>
        <el-form-item
          v-if="item.inputType == 'upload'"
          :label="item.label"
          :prop="item.prop"
        >
          <upload
            :prop="item.prop"
            :fileLists="formData[item.prop]"
            :action="item.action"
            :multiple="item.multiple"
            :limit="item.limit"
            :headers="item.headers"
            @uploadFiles="uploadFiles"
          />
        </el-form-item>
      </el-col>
      <slot name="button"></slot>
    </el-row>
  </el-form>
</template>

<script setup lang="ts">
import upload from "./upload.vue";
import { MdEditor } from 'md-editor-v3';
import 'md-editor-v3/lib/style.css';
import { reactive, ref } from "vue";
import type { FormInstance } from "element-plus";
import { ElMessage } from "element-plus";
import { saveForm,uploadImage } from "@/api/index";
import { setStorage, getStorage } from "@/utils/storage";
let props = defineProps({
  formData: {
    type: Object,
    require: true,
    default: {},
  },
  formItems: {
    type: Object,
    required: true,
    default: {},
  },
});
let formColumn = reactive(props.formItems);
const FormRef = ref<FormInstance | undefined>();

const emit = defineEmits(["changeForm"]);
const submitForm = (params: any) => {
  if (!FormRef) return;
  const promise = new Promise((resolve, reject) => {
    FormRef.value!.validate((valid, fields) => {
      if (valid) {
        saveForm(params).then((res: any) => {
          if (res.code == 200) {
            ElMessage({
              showClose: true,
              message: res.message,
              type: "success",
            });
            resolve({ code: 200 });
          } else {
            ElMessage({
              showClose: true,
              message: res.message,
              type: "error",
            });
            resolve({ code: 200 });
          }
        });
      } else {
        resolve({ code: 201 });
        ElMessage({
          showClose: true,
          message: "表单校验未通过",
          type: "error",
        });
      }
    });
  });
  return promise;
};
const resetForm = () => {
  if (!FormRef) return;
  FormRef.value!.resetFields();
};
const saveMd = (item: any) => {
  setStorage(item.prop, FormData[item.prop]);
};
const uploadFiles = (prop: any, val: any) => {
  props.formData[prop] = val;
};
//上传图片
const onUploadImg = async (files:any, callback:any) => {
  const res = await Promise.all(
    files.map((file:any) => {
      return new Promise((rev, rej) => {
        const form = new FormData();
        form.append('file', file);
        uploadImage({file:file}).then((respons:any) => {
          rev(respons)
        }).catch((error:any) =>rej(error))
      });
    })
  );
  callback(res.map((item) =>'http://www.lihynotes.cn:81/' +'upload/' + item.data.newFilename));
}
onMounted(() => {});
const changeForm = (prop: any, val: any, option: any) => {
  emit("changeForm", prop, val, option);
};
defineExpose({
  submitForm,
  resetForm,
});
</script>

<style scoped></style>
